<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/29
 * Time: 15:34
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;

AppAsset::addCss($this,$base . '/app/css/bar-detail.css?V=0.0.4');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');

?>

<div class="detail-container" style="width: 74rem">
    <p class="top-title">基本信息</p>

    <div style="float: left">
        <p class="item-title"><span class="necessary-note">*</span>商家名称</p>
        <input id="barName" class="input-row" placeholder="请输入" value="<?= $bar['bar_name']?>">
    </div>

    <div class="clear"></div>

    <div style="float: left;">
        <p class="item-title"><span class="necessary-note">*</span>地区选择</p>
        <div class="dropdown" style="font-size: 1.3rem">
            <button type="button" class="btn dropdown-toggle" id="dropdownMenu" city-id="<?= $bar['city_code']?>"
                    data-toggle="dropdown">
                未选择
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
                <li role="presentation" >
                    <a role="menuitem" tabindex="-1" href="javascript:chooseCity('179','杭州市')">杭州市</a>
                </li>
                <?php for($index=0;$index<count($cities);$index++){?>
                    <li role="presentation" >
                        <a role="menuitem" tabindex="-1" href="javascript:chooseCity('<?= $cities[$index]['city_code']?>','<?= $cities[$index]['city_name']?>')"><?= $cities[$index]['city_name']?></a>
                    </li>
                <?php }?>
            </ul>
        </div>
    </div>

    <div style="float: left;    margin-left: 2.67rem;">
        <p class="item-title"><span class="necessary-note">*</span>具体地址</p>
        <input id="address" class="input-row" placeholder="选择定位确定地理位置" value="<?= $bar['bar_address']?>" disabled>
        <button class="location" onclick="showMap()">定位</button>
    </div>

    <div class="clear"></div>

    <div style="float: left;">
        <p class="item-title"><span class="necessary-note">*</span>营业时间</p>
        <input id="barTime" class="input-row" placeholder="请输入" value="<?= $bar['business_hours']?>">
    </div>

    <div style="float: left;margin-left: 6.67rem;">
        <p class="item-title"><span class="necessary-note">*</span>商家类型</p>

        <div class="dropdown" style="font-size: 1.3rem">
            <button type="button" class="btn dropdown-toggle" id="dropdownMenu2" bar-type="<?= $bar['bar_type']?>"
                    data-toggle="dropdown">
                未选择
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
                <li role="presentation" >
                    <a role="menuitem" tabindex="-1" href="javascript:chooseBarType('清吧',1)">清吧</a>
                </li>
                <li role="presentation" >
                    <a role="menuitem" tabindex="-1" href="javascript:chooseBarType('夜店',2)">派对吧</a>
                </li>
                <li role="presentation" >
                    <a role="menuitem" tabindex="-1" href="javascript:chooseBarType('livehouse',3)"> 音乐house</a>
                </li>
            </ul>
        </div>
    </div>

    <div class="clear"></div>

    <p class="item-title"><span class="necessary-note">*</span>图片（最多20张）</p>
    <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file2" name="upload-file2" onchange="thumbImage(this)" style="display: none">
    <div class="image-container">
        <div id="imageChoose" class="image-item" onclick="showPic(0)">
            <img class="image-choose" src="<?= $base?>/app/images/dynamic/default-logo.png">
        </div>
    </div>

    <div class="clear"></div>

    <p class="item-title"><span class="necessary-note">*</span>LOGO</p>
    <div class="logo-container">
        <div id="logoChoose" class="logo-item" onclick="showPic(1)">
            <img id="logoValue" class="logo-value" src="<?= $bar['bar_logo']?>">
        </div>
    </div>

    <div style="float: left">
        <p class="item-title"><span class="necessary-note">*</span>商家公告</p>
        <input id="barNotice" class="input-row" placeholder="请输入" value="<?= $bar['bar_notice']!="%Null%"?$bar['bar_notice']:""?>">
    </div>

    <div class="clear"></div>

    <div style="float: left">
        <p class="item-title"><span class="necessary-note">*</span>商家头条</p>
        <input id="barHeadline" class="input-row" placeholder="请输入" value="<?= $bar['bar_headline']!="%Null%"?$bar['bar_headline']:""?>">
        <input id="headlineUrl" class="input-row" placeholder="请输入头条链接" value="<?= $bar['headline_url']!="%Null%"?$bar['headline_url']:""?>">
    </div>

    <div class="clear"></div>

    <div style="float: left">
        <p class="item-title"><span class="necessary-note">*</span>商家推荐</p>
        <input id="barRecommend" class="input-row" placeholder="请输入" value="<?= $bar['bar_recommend']!="%Null%"?$bar['bar_recommend']:""?>">
    </div>

    <div class="clear"></div>

    <div class="button-div" style="margin-top: 1.67rem">保存</div>
</div>

<div id="chooseAddress" class="public-dialog" hidden="hidden">
    <div class="map">
        <label>地图打点</label>
        <img class="myMapClose" src="<?= $base?>/app/images/close.png" onclick="closeMap()">
        <div id="content">
            <div id="gps" hidden="hidden" ><?= $bar['bar_lng'].','.$bar['bar_lat']?><br></div>
            <input id="placeName" value="<?= $bar['bar_address']?>">
            <img class="locationButton" src="<?= $base?>/app/images/location.png" onclick="find()">
            <!--                    <input id="find" type="button" value="定位地址" onclick = "find()">-->
            <div id="allmap"></div>
            <div  style="text-align: center">
                <button class="save2" onclick="saveAddress()">保存地址</button>
                <button class="myCancel" onclick="closeMap()">取消</button>
            </div>

        </div>
    </div>
</div>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=OMBI9oyDFdUn5pVw3QlzW2ar5593A3L1"></script>
<script>

    var barId = '<?= $bar['bar_id']?>';
    var cities = eval(<?php echo json_encode($cities)?>);

    function setPhotos(photos){
        if(photos.length > 0){
            var arr = photos.split(";");
            for(var index=0;index<arr.length;index++){
                var imgHtml = '<div class="image-item">'+
                    '<img class="image-delete" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_found_picture_close.png" onclick="deleteImage(this)">'+
                    '<img class="image-value" src="'+arr[index]+'">'+
                    '</div>';

                $(".image-container").append(imgHtml);

                if($(".image-value").length == photoMax)
                    $("#imageChoose").hide();
            }
        }
    }

    function setCityName(cityCode){
        for(var index=0;index<cities.length;index++){
            if(cities[index]['city_code'] == cityCode){
                $("#dropdownMenu").text(cities[index]['city_name']);
                break;
            }
        }
    }

    var barTypeNames = ["清吧","派对吧","音乐house"];
    function setBarType(barType){
        $("#dropdownMenu2").text(barTypeNames[parseInt(barType) - 1]);
    }
</script>

<script>
    $(function(){

        //选择图片点击事件
        $(".myClose").click(function(){
            closePic();
        });
        $(".select-img").click(function(){
            upload(this);
        });
        $(".upload-img").click(function(){
            uploadImage(this);
        });
        //选择图片结束

        $(".button-div").click(function(){
            createBarController.createBarFunc();
        });

        setPhotos('<?= $bar['bar_photos']?>');
        setCityName('<?= $bar['city_code']?>');
        setBarType('<?= $bar['bar_type']?>');
    });

    function chooseCity(cityCode,cityName){
        $("#dropdownMenu").attr("city-id",cityCode);
        $("#dropdownMenu").text(cityName);
    }

    function chooseBarType(name,type){
        $("#dropdownMenu2").attr("bar-type",type);
        $("#dropdownMenu2").text(name);
    }

    var createBarController = {
        createBarApi:"bar",
        createBarFunc:function(){

            var barName = $("#barName").val();
            barName = barName.replace(/[&\|\\\*^%$#@\-]/g,"");
            if(isEmpty(barName)){
                alert("请输入商家名称");
                return;
            }

            var cityCode = $("#dropdownMenu").attr("city-id");
            if(cityCode == -1){
                alert("请选择商家所在城市");
                return;
            }

            var barAddress = $("#address").val();
            if(isEmpty(barAddress)){
                alert("请填写商家详细地址");
                return;
            }

            var gps = document.getElementById("gps").innerHTML;
            var lng = gps.split(',')[0];
            var lat = gps.split(',')[1].split('<')[0];

            var barType = $("#dropdownMenu2").attr("bar-type");
            if(barType == -1){
                alert("请选择商家类型");
                return;
            }

            var logoImage = $("#logoValue").attr("src");
            if(logoImage.indexOf("http") == -1) {
                alert("请上传商家LOGO");
                return;

            }

            var param = {
                bar_id:barId,
                bar_name:barName,
                city_code:cityCode,
                bar_address:barAddress,
                bar_lat : lat,
                bar_lng : lng,
                bar_type : barType,
                bar_logo : logoImage
            };

            var barNotice = $("#barNotice").val();
            if(barNotice.length > 0)
                param.bar_notice = barNotice;
            else
                param.bar_notice = "%Null%";

            var barHeadline = $("#barHeadline").val();
            var headlineUrl = $("#headlineUrl").val();
            if(barHeadline.length > 0){
                param.bar_headline = barHeadline;

                if(headlineUrl.length < 1){
                    alert("请输入商家头条链接");
                    return;
                }
                param.headline_url = headlineUrl;
            }else{
                param.bar_headline = "%Null%";
                param.headline_url = "%Null%";
            }

            var barRecommend = $("#barRecommend").val();
            if(barRecommend.length > 0)
                param.bar_recommend = barRecommend;
            else
                param.bar_recommend = "%Null%";

            if($(".image-value").length > 0)
                param.bar_photos = getImageValue();
            else
                param.bar_photos = "";

            var businessHours = $("#barTime").val();
            if(!isEmpty(businessHours))
                param.business_hours = businessHours;

            $('.loading-area').show();
            sendAjax(this.createBarApi,"POST",param,false,function(res){
                $('.loading-area').hide();
                var data = JSON.parse(res);
               if(data.code == 0){
                   location.reload();
               } else
                   alert(data.msg);
            });
        }
    };

    function isEmpty(content){
        return content.length < 1;
    }

    //地图
    //显示与隐藏地图
    function showMap(){
        $('#chooseAddress').show();
        $('.part-two').hide();
        $('.part-three').hide();
        $('.part-four').hide();
    }
    function closeMap(){
        $('#chooseAddress').hide();
        $('.part-two').show();
        $('.part-three').show();
        $('.part-four').show();
    }
    //保存地址
    function saveAddress(){
        $('#address').val($('#placeName').val());
        $('#chooseAddress').hide();
        $('.part-two').show();
        $('.part-three').show();
        $('.part-four').show();
    }


    // 百度地图API功能
    var city = "";
    var map = new BMap.Map("allmap");
    var myCity = new BMap.LocalCity();//获取当前城市
    map.addControl(new BMap.NavigationControl());  	//添加地图导航控件
    myCity.get(myFun);
    function myFun(result){
        city = result.name;
        map.centerAndZoom(city,16);//设置地图定位的城市和缩放级别
        // alert(city);
    }

    var geoc = new BMap.Geocoder();

    //初始化定位
    if ($('#placeName').val()){
        find();
    }

    //单击地图获取当前经纬度和地址
    map.addEventListener("click",function(e){
        var pt = e.point;
        map.clearOverlays(); //清除地图覆盖物
        var mk = new BMap.Marker(e.point);
        map.addOverlay(mk);
        geoc.getLocation(pt, function(rs){
            var addComp = rs.addressComponents;
            document.getElementById("gps").innerHTML= e.point.lng + "," + e.point.lat + "</br>" ;//显示当前位置的经纬度
            document.getElementById("placeName").value = addComp.province + "" + addComp.city + "" + addComp.district + "" + addComp.street + "" + addComp.streetNumber;
            //显示当前地址
        });

    });

    //通过地址来定位
    function find(){
        map.clearOverlays();
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        var place =  document.getElementById("placeName").value;
        myGeo.getPoint(place, function(point){
            if (point) {
                map.centerAndZoom(point, 16);
                map.addOverlay(new BMap.Marker(point));
                document.getElementById("gps").innerHTML= point.lng + "," + point.lat + "</br>" ;//显示当前位置的经纬度
            }else{
                alert("您选择地址没有解析到结果!");
            }
        }, "杭州市");

    }

    //图片上传
    var photoMax = 20;
    var imageType = 0;

    //点击图片来选择上传的图片
    function upload(button){
//        $(button).css('background-color','#77778F').css('color','white');
        var intputId = 'upload-file2';
        document.getElementById(intputId).click();
    }

    function showPic(chooseImageType){
        imageType = chooseImageType;
        $('.choose-area').show();
    }

    function closePic(){
        $('.choose-area').hide();
        $('.pic-area').empty();
        if (!$('.pic-area img').length){
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        $('.upload').css('background-color','white').css('color','#A8A8A8');
        $('.select-img').css('background-color','white').css('color','#A8A8A8');
        //清除input file 的value,可以触发下次的onchange;
        $('#upload-file2').val('');

        $('.upload-img').css('background','white').prop('disabled',false);

    }
    //选择图片之后的操作

    //图片缩略图处理
    function thumbImage(input){
        //设置宽高比
        var w = 1;
        var h = 1;

        //再次点击上传时清除之前的截图操作
        if ($('.jcrop-holder').length){
            $('.pic-area').empty();
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        if (typeof (FileReader) != "undefined") {
            var regex = /(.jpg|.jpeg|.png)$/;
            $($(input)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
//                        var img = $(input).prev();
                        var img = $('#pic-area-img');
                        $(img).attr('src',e.target.result);
                        var realWidth;//真实的宽度
                        var realHeight;//真实的高度
                        //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
                        $("<img/>").attr("src", $(img).attr('src')).load(function() {
                            /*
                             如果要获取图片的真实的宽度和高度有三点必须注意
                             1、需要创建一个image对象：如这里的$("<img/>")
                             2、指定图片的src路径
                             3、一定要在图片加载完成后执行如.load()函数里执行
                             */
                            realWidth = this.width;
                            realHeight = this.height;
                            var width = $('.pic-area').css('width').split('p')[0];
                            var height = $('.pic-area').css('height').split('p')[0];
//                            console.log(realWidth,realHeight,width,height)
                            if(realWidth<width && realHeight<height){
                                $(img).css("width",realWidth+'px').css("height",realHeight+'px');
                            }else{
                                //如果真实的宽高比大于给定的宽高比就按照宽度100%显示
                                if(realWidth/realHeight >= width/height){
                                    $(img).css("width","99%").css("height","auto");
                                }
                                else{//如果小于给定的宽高比按照原尺寸显示
                                    $(img).css("width","auto").css("height","99%");
                                }
                            }
//                            console.log(realWidth,$(img).css("width").split('p')[0]);
                            var ratio = realWidth/$(img).css("width").split('p')[0];
//                            console.log(ratio)
                            $('#pic-area-img').show();
                            var jcrop_api;
                            $('#pic-area-img').Jcrop({
                                aspectRatio: w / h,
                                onSelect:uodateCoords,
                                setSelect:[0,0,600,600]
                            },function(){
                                jcrop_api = this;
                            });
                            function uodateCoords(c){
                                $('#x').val(c.x*ratio);
                                $('#y').val(c.y*ratio);
                                $('#w').val(c.w*ratio);
                                $('#h').val(c.h*ratio);
                            }
                            var jcropWidth =   $(img).css('width').split('p')[0];
                            var jcropHeight =   $(img).css('height').split('p')[0];
                            var marginLeft = (width-jcropWidth)/2;
                            var marginTop = (height-jcropHeight)/2;
                            $('.jcrop-holder').css("margin-top",marginTop + 'px');
                            $('.jcrop-holder').css("margin-left",marginLeft + 'px');
//                            jcrop_api.setSelect([marginLeft,marginTop,336,336]);
                        });
                    }
                    reader.readAsDataURL(file[0]);
                }else {
                    alert(file[0].name + " is not a valid image file.");
                    return false;
                }
            })
        }else{
            alert("This browser does not support HTML5 FileReader.");
        }
    }
    //ajax 异步上传图片
    function uploadImage(button){
        //定义允许上传的图片格式 在前台就可以直接判断，不合法的格式将不会上传
        //尺寸限制

        var intputId = 'upload-file2';
        var limit = 8 * 1024 * 1024;

        var file = $('#'+intputId).get(0).files;

//            $($(button).parent().prev().children()[1]).get(0).files;
        var filetype = ['jpg','jpeg','png','gif'];
        if(file.length){
            var fi = file[0]; //得到文件信息
            //判断文件格式是否是图片 如果不是图片则返回false
            var index = fi.name.lastIndexOf('.');
            var fname = [fi.name.substring(0,index),fi.name.substring(index+1)];
            if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                alert('文件格式不支持');
                return ;
            }
            //实例化h5的fileReader
            var fr = new FileReader();
            fr.readAsDataURL(fi); //以base64编码格式读取图片文件
            fr.onload = function(frev){
                pic = frev.target.result; //得到结果数据
                //开始上传之前，预览图片
//                $('#img').attr('src',pic);
                //使用ajax 利用post方式提交数据
                var x = $('#x').val();
                var y= $('#y').val();
                var width= $('#w').val();
                var height= $('#h').val();
                if (width == 0 && height == 0){
                    alert('请选择图片');
                    return;
                }
                if(fi.size > limit){
                    alert("上传照片不得大于8M");
                    return;
                }
                $('.loading-area').show();
                $(button).css('background','#CCCCCC').prop('disabled',true);
                $.post(
                    'img-upload',
                    {
                        message:pic,
                        filename:fname[0],
                        filetype:fname[1].toLowerCase(),
                        filesize:fi.size,
                        x:x,
                        y:y,
                        width:width,
                        height:height,
                        limit:limit
                    },
                    function(data){
                        data = eval('('+data+')');
                        if(data.code == 1){
                            $('.loading-area').hide();
                            alert('上传失败');
                        }else if(data.code == 0){

                            if(imageType == 0){
                                var imgHtml = '<div class="image-item">'+
                                    '<img class="image-delete" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_found_picture_close.png" onclick="deleteImage(this)">'+
                                    '<img class="image-value" src="'+data.imgSrc+'">'+
                                    '</div>';

                                $(".image-container").append(imgHtml);

                                if($(".image-value").length == photoMax)
                                    $("#imageChoose").hide();
                            }else{
                                $("#logoValue").attr("src",data.imgSrc);
                            }

                            $('.loading-area').hide();
                            alert('上传成功');
                            closePic();
                        }else if(data.code == 2){
                            var size = parseInt(parseInt(data.size)/1000);
                            if (size>1000)
                                size = parseInt(size/1000) + 'M';
                            else
                                size += 'KB';
                            var msg = data.msg + ',当前图片尺寸为:' + size;
                            $('.loading-area').hide();
                            alert(msg);
                        }
                    }
                )
                    .fail(function(xhr,status,error){
//                    console.log(xhr,status,error)
                        $('.loading-area').hide();
                        alert('上传失败')
                    })
            }
        }else
            alert('请选择图片');
    }

    function deleteImage(view){
        $(view).parent().remove();
        if($(".image-value").length < photoMax)
            $("#imageChoose").show();
    }

    function getImageValue(){
        var imageString = "";
        $(".image-value").each(function() {
            imageString +=$(this).attr("src") + ";";
        });
        var reg=/;$/gi;
        return imageString.replace(reg,"");
    }
</script>